'''
计算SUV值
生成SUVSlice
'''

import os
import numpy as np
import csv
import pydicom
import cv2
import pandas as pd

def is_in_circle(x,y,petx, pety,r):
    return (x-petx)**2+(y-pety)**2 <= r*r

def calculate_suv():
    myfile = open('D:/lung_cancer/data/data_augmentation/divide_csv/over_sampling_five/augement_test4.csv')
    data = []
    lines = csv.reader(myfile)
    for line in lines:
        data.append(line)

    new_data = []
    columns = data[0]
    columns.append('SUVSlice_Path')
    columns.append('global_suvmax')
    columns.append('local_suvmax')
    columns.append('local_suvmin')
    columns.append('local_suvavg')
    columns.append('local_suvstd')
    columns.append('local_suvvar')
    print(columns)
    num = 1
    for line in data[1:]:
        PatientID = str(int(line[0]))
        instancenumber = str(line[1])
        cancer_type = str(int(line[5]))
        pet_array = np.load('D:/lung_cancer/data/data_augmentation/divide_csv/over_sampling_five/'+line[-2])
        PatientWeight = float(line[20])
        DecayFactor = float(line[28])
        TotalDose = float(line[24])
        HalfLife = float(line[27])
        t0 = str(line[25].split('.')[0]).rjust(6, '0')
        t1 = str(int(line[26].split('.')[0])).rjust(6, '0')
        intercept = float(line[17])
        slope = float(line[19])
        # 时间单位：hhmmss(小时分秒)
        interval_t = 3600 * (int(t1[:2]) - int(t0[:2])) + 60 * (int(t1[2:4]) - int(t0[2:4])) + (int(t1[4:6]) - int(t0[4:6]))
        coefficient = 1000.0 * np.exp(interval_t / HalfLife * np.log(2)) / (TotalDose / PatientWeight)  # 不使用DecayFactor
        # coefficient = DecayFactor * 1000.0 * np.exp(interval_t / HalfLife * np.log(2)) / (TotalDose / PatientWeight)  # 使用DecayFactor

        pet_array = pet_array.astype(np.int32)
        if slope != 1:
            pet_array = slope * pet_array.astype(np.float64)
            pet_array = pet_array.astype(np.int32)
        pet_array += np.int32(intercept)

        local_suvmax = calculate_local_suvmax(pet_array, coefficient, int(line[2]), int(line[3]), int(line[4]))
        global_suvmax = calculate_global_suvmax(pet_array, coefficient)
        local_suvmin = calculate_local_suvmin(pet_array, coefficient, int(line[2]), int(line[3]), int(line[4]))
        local_suvavg = calculate_local_suvavg(pet_array, coefficient, int(line[2]), int(line[3]), int(line[4]))
        local_suvstd = calculate_local_suvstd(pet_array, coefficient, int(line[2]), int(line[3]), int(line[4]))
        local_suvvar = calculate_local_suvvar(pet_array, coefficient, int(line[2]), int(line[3]), int(line[4]))
        print('%d--%s--->%s--->local_suvmax:%.2f-->global_suvmax:%.2f-->local_suvmin:%.2f-->local_suvavg:%.2f-->'
              'local_suvstd:%.2f-->local_suvvar:%.2f'
              % (num,PatientID ,line[0], local_suvmax, global_suvmax, local_suvmin, local_suvavg, local_suvstd, local_suvvar))

        num = num+1

        SUVSlice_path = 'Slice/'+str(PatientID)+'/SUVSlice/'+instancenumber+'.npy'

        line.append(SUVSlice_path)
        line.append(global_suvmax)
        line.append(local_suvmax)
        line.append(local_suvmin)
        line.append(local_suvavg)
        line.append(local_suvstd)
        line.append(local_suvvar)
        new_data.append(line)

    df = pd.DataFrame(new_data, columns=columns)
    df.to_csv('D:/lung_cancer/data/data_augmentation/divide_csv/over_sampling_five/augement_test5.csv', index=False)


def calculate_local_suvmax(pet_array, coefficient, petx, pety, petr):
    suvmax = 0
    for col in range(pety - petr, pety + petr):
        for row in range(petx - petr, petx + petr):
            if is_in_circle(row, col, petx, pety, petr):
                suv = pet_array[col, row]*coefficient
                if suv > suvmax:
                    suvmax = suv
    return suvmax

def calculate_global_suvmax(pet_array, coefficient):
    suvmax = 0
    for col in range(0, 512):
        for row in range(0, 512):
            suv = pet_array[col, row] * coefficient
            if suv > suvmax:
                suvmax = suv
    return suvmax

def calculate_local_suvmin(pet_array, coefficient, petx, pety, petr):
    suvmin = 100
    for col in range(pety - petr, pety + petr):
        for row in range(petx - petr, petx + petr):
            if is_in_circle(row, col, petx, pety, petr):
                suv = pet_array[col, row] * coefficient
                if suv < suvmin:
                    suvmin = suv
    return suvmin

def calculate_local_suvavg(pet_array, coefficient, petx, pety, petr):
    suvsum = 0
    num = 0
    for col in range(pety - petr, pety + petr):
        for row in range(petx - petr, petx + petr):
            if is_in_circle(row, col, petx, pety, petr):
                suvsum = suvsum+pet_array[col, row] * coefficient
                num = num+1
    return suvsum/num

def calculate_local_suvstd(pet_array, coefficient, petx, pety, petr):
    plot_list = []
    for col in range(pety - petr, pety + petr):
        for row in range(petx - petr, petx + petr):
            if is_in_circle(row, col, petx, pety, petr):
                suv = pet_array[col, row] * coefficient
                plot_list.append(suv)
    suvstd = np.std(plot_list)
    return suvstd

def calculate_local_suvvar(pet_array, coefficient, petx, pety, petr):
    plot_list = []
    for col in range(pety - petr, pety + petr):
        for row in range(petx - petr, petx + petr):
            if is_in_circle(row, col, petx, pety, petr):
                suv = pet_array[col, row] * coefficient
                plot_list.append(suv)
    suvvar = np.var(plot_list)
    return suvvar

def save_SUVSlice():
    myfile = open('D:/lung_cancer/data/data_augmentation/divide_csv/over_sampling_five/augement_test4.csv')
    data = []
    lines = csv.reader(myfile)
    for line in lines:
        data.append(line)

    num = 1
    for line in data[1:]:
        PatientID = str(int(line[0]))
        cancer_type = str(int(line[5]))

        instancenumber = str(int(line[1]))

        pet_array = np.load('D:/lung_cancer/data/data_augmentation/divide_csv/over_sampling_five/' + line[-2])
        PatientWeight = float(line[20])
        DecayFactor = float(line[28])
        TotalDose = float(line[24])
        HalfLife = float(line[27])
        t0 = str(line[25].split('.')[0]).rjust(6, '0')
        t1 = str(int(line[26].split('.')[0])).rjust(6, '0')
        intercept = float(line[17])
        slope = float(line[19])
        # 时间单位：hhmmss(小时分秒)
        interval_t = 3600 * (int(t1[:2]) - int(t0[:2])) + 60 * (int(t1[2:4]) - int(t0[2:4])) + (
                    int(t1[4:6]) - int(t0[4:6]))
        coefficient = 1000.0 * np.exp(interval_t / HalfLife * np.log(2)) / (TotalDose / PatientWeight)  # 不使用DecayFactor
        # coefficient = DecayFactor * 1000.0 * np.exp(interval_t / HalfLife * np.log(2)) / (TotalDose / PatientWeight)  # 使用DecayFactor

        pet_array = pet_array.astype(np.int32)
        if slope != 1:
            pet_array = slope * pet_array.astype(np.float64)
            pet_array = pet_array.astype(np.int32)
        pet_array += np.int32(intercept)


        suv_array = pet_array*coefficient

        # suv_array = suv_array/50.0  #经过计算，suv最大值不超过50，这里对suv值进行了除50操作，达到归一化的作用

        path = 'D:/lung_cancer/data/data_augmentation/divide_csv/over_sampling_five/Slice/'+PatientID+'/SUVSlice/'
        if not os.path.exists(path):
            os.makedirs(path)
        np.save(path+'/'+instancenumber+'.npy', suv_array)

        print('%d --->%s is saved!' %(num, PatientID))
        num = num+1

if __name__ == '__main__':
    # save_SUVSlice()
    calculate_suv()

